package login.servlet;

import login.dao.UserDao;
import login.dao.UserDaoImpl;
import login.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Administrator
 * @Date 2020/5/29 8:45
 **/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*1.设置post请求编码（解决中文乱码问题）
        * 2.获取请求参数（用户数量的内容）
        * 3.若需要，将参数封装成对象
        * 4.调用dao层的方法完成登陆功能（查询操作）
        * 5.根据dao层返回值
        * 若不为空，表示用户名密码正确，将用户名保存在域对象，转发到succServlet
        * 若为空，表示用户名密码错误，转发到failServlet*/
        req.setCharacterEncoding("utf-8");
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        UserDao dao=new UserDaoImpl();
        User login = dao.login(name, password);
        if (login!=null){
            /*登陆成功
            * 1)把用户名保存在域对象
            * 2）转发到succServlet*/
            req.setAttribute("user",login.getName());
            req.getRequestDispatcher("/successServlet").forward(req,resp);
        }else {
            /*用户名或密码错误，登录失败
            * 1)错误信息保存在域对象
            * 2）转发到failServlet*/
            req.setAttribute("login_error","用户名或密码错误");
            req.getRequestDispatcher("/failServlet").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
